//
//  BiuServer.swift
//  Biubiubiu
//
//  Created by DevWhan on 2019/5/4.
//  Copyright © 2019 DevWhan. All rights reserved.
//

import Cocoa
import Swifter

class BiuServer {
    public let server = HttpServer()
    let prePath = "Biu"
    
    init(project: Project) {
        server["/\(prePath)/:path"] = shareFilesFromDirectory(project.mainDirectory())
        startServer()
    }
    
    private func startServer(port: in_port_t = 8081, maximumOfAttempts: Int = 5) {
        
        // Stop the retrying when the attempts is zero
        if maximumOfAttempts == 0 {
            return
        }
        
        do {
            try server.start(port)
            print("Server has started ( port = \(try server.port()) ). Try to connect now...")
        } catch SocketError.bindFailed(let message) where message == "Address already in use" {
            startServer(port: in_port_t.random(in: 8081..<10000), maximumOfAttempts: maximumOfAttempts - 1)
        } catch {
            print("Server start error: \(error)")
        }
    }
}
